import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  OnDestroy,
} from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { combineLatest, forkJoin, Subject } from 'rxjs';
import { first, takeUntil } from 'rxjs/operators';
import {
  AlbumService,
  AlbumTrackArgs,
} from '../../services/apis/album.service';
import {
  AlbumInfo,
  Anchor,
  RelateAlbum,
  Track,
} from '../../services/apis/types';
import { CategoryService } from '../../services/business/category.service';
import { PlayerService } from '../../services/business/player.service';
import { PageService } from '../../services/tools/page.service';
import { MessageService } from '../../share/components/message/message.service';
import { IconType } from '../../share/directives/icon/type';
interface MoreState {
  full: boolean;
  label: string;
  icon: IconType;
}
@Component({
  selector: 'app-album',
  templateUrl: './album.component.html',
  styleUrls: ['./album.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AlbumComponent implements OnInit, OnDestroy {
  size = 16;
  albumInfo: AlbumInfo;
  score: number;
  anchor: Anchor;
  relateAlbums: RelateAlbum[];
  tracks: Track[] = [];
  total = 0;
  trackParams: AlbumTrackArgs = {
    albumId: '',
    sort: 1,
    pageNum: 1,
    pageSize: 30,
  };
  moreState: MoreState = {
    full: false,
    label: '显示全部',
    icon: 'arrow-down-line',
  };
  articleHeight = 0;
  formValues = this.fb.group({
    name: [''],
    size: [{ value: 24, disabled: true }],
  });
  checked = false;
  currentCheck = ['apple'];
  checkOpts = [
    {
      label: '苹果',
      value: 'apple',
    },
    {
      label: '橘子',
      value: 'Orange',
    },
  ];
  selectTracks = [];
  private destory$ = new Subject<void>();
  private currentTrack: Track;
  private playing = false;
  constructor(
    private route: ActivatedRoute,
    private albumService: AlbumService,
    private categoryServe: CategoryService,
    private cdr: ChangeDetectorRef,
    private fb: FormBuilder,
    private playService: PlayerService,
    private messageService:MessageService, 
    private pageService: PageService
  ) {}

  rateChanged(value: number) {
    console.log(value);
  }
  submit() {
    console.log(this.formValues.value);
  }
  sizeChange(value: number): void {
    console.log(value, 'sc');
  }
  ngOnInit(): void {
    this.route.paramMap.pipe(takeUntil(this.destory$)).subscribe((paramMap) => {
      this.trackParams.albumId = paramMap.get('albumId');
      this.initPageData();
      this.watchPlayer();
    });
     
  }
  private watchPlayer(): void {
    combineLatest(
      this.playService.getCurrentTrack(),
      this.playService.getPlaying()
    )
      .pipe(takeUntil(this.destory$))
      .subscribe(([track, playing]) => {
        this.currentTrack = track;
        this.playing = playing;
        this.cdr.markForCheck();
      });
  }
  checkedChange(checked: boolean, track: Track) {
    const targetIndex = this.selectIndex(track.trackId);
    if (checked) {
      if (targetIndex === -1) {
        this.selectTracks.push(track);
      }
    } else {
      if (targetIndex > -1) {
        this.selectTracks.splice(targetIndex, 1);
      }
    }
    console.log(this.selectTracks);
  }
  isChecked(id: number): boolean {
    return this.selectIndex(id) > -1;
  }
  isCheckedAll(): boolean {
    if (this.selectTracks.length >= this.tracks.length) {
      return this.tracks.every((item) => {
        return this.selectIndex(item.trackId) > -1;
      });
    }
    return false;
  }
  private selectIndex(id: number): number {
    return this.selectTracks.findIndex((item) => item.trackId === id);
  }
  checkedAllChange(checked): void {
    this.tracks.forEach((item) => {
      const targetIndex = this.selectIndex(item.trackId);
      if (checked) {
        if (targetIndex === -1) {
          this.selectTracks.push(item);
        }
      } else {
        if (targetIndex > -1) {
          this.selectTracks.splice(targetIndex, 1);
        }
      }
    });
  }
  changePage(page: number): void {
    if (this.trackParams.pageNum !== page) {
      this.trackParams.pageNum = page;
      this.updateTracks();
    }
  }
  updateTracks(): void {
    this.albumService.tracks(this.trackParams).subscribe((res) => {
      this.tracks = res.tracks;
      this.total = res.trackTotalCount;
      this.cdr.markForCheck();
    });
  }
  private initPageData(): void {
    forkJoin([
      this.albumService.album(this.trackParams.albumId),
      this.albumService.albumScore(this.trackParams.albumId),
      this.albumService.relateAlbums(this.trackParams.albumId),
    ])
      .pipe(first())
      .subscribe(([albumInfo, score, relateAlbums]) => {
        this.albumInfo = { ...albumInfo.mainInfo, albumId: albumInfo.albumId };
        this.score = score;
        this.anchor = albumInfo.anchorInfo;
        // this.tracks = albumInfo.tracksInfo.tracks;
        // this.total = albumInfo.tracksInfo.trackTotalCount;
        this.updateTracks();
        this.relateAlbums = relateAlbums.slice(0, 10);
        // const category = localStorage.getItem('pinying');
        // const { categoryPinyin } = this.albumInfo.crumbs;
        // if (category != categoryPinyin) {
        //   this.categoryServe.setCategory(categoryPinyin);
        // }
        this.categoryServe
          .getCategory()
          .pipe(first())
          .subscribe((category) => {
            const { categoryPinyin } = this.albumInfo.crumbs;
            if (category != categoryPinyin) {
              this.categoryServe.setCategory(categoryPinyin);
            }
          });
        this.categoryServe.setSubCategory([this.albumInfo.albumTitle]);
        this.pageService.setPageInfo(this.albumInfo.albumTitle, "专辑详情", "小说，音乐");  
        this.cdr.markForCheck();
      });
  }
  toggleMore() {
    this.moreState.full = !this.moreState.full;
    if (this.moreState.full) {
      this.moreState.label = '收起';
      this.moreState.icon = 'arrow-up-line';
    } else {
      this.moreState.label = '显示全部';
      this.moreState.icon = 'arrow-down-line';
    }
  }
  trackByTracks(index: number, item: Track): number {
    return item.trackId;
  }
  play(needPlay:boolean):void {
    if (this.selectTracks.length) {
      if (needPlay) {
        this.playService.playTracks(this.selectTracks);
      }else {
        this.playService.addTracks(this.selectTracks);
        this.messageService.warning('已添加');
      }
      this.setAlbumInfo();
      this.checkedAllChange(false);
    }else {
      this.messageService.warning("未选择任何曲目");
    }
  }
  private setAlbumInfo() {
    if (!this.currentTrack) {
      this.playService.setAlbum(this.albumInfo);
    }
  }
  //播放全部
  playAll(): void {
    this.playService.setTracks(this.tracks);
    this.playService.setCurrentIndex(0);
    this.playService.setAlbum(this.albumInfo);
  }
  toggleTrack(track: Track, act: 'play' | 'pause'): void {
    if (act == 'pause') {
      this.playService.setPlaying(false);
    } else {
      this.setAlbumInfo();
      this.playService.playTrack(track);
    }
  }
  itemCls(id: number): string {
    let result = 'item-name ';
    if (this.currentTrack) {
      if (this.playing) {
        if (this.currentTrack.trackId === id) {
          result += 'item-name-playing';
        }
      } else {
        if (this.currentTrack.trackId === id) {
          result += 'item-name-pause';
        }
      }
    }
    return result;
  }
  ngOnDestroy(): void {
    this.destory$.next();
    this.destory$.complete();
  }
}
